import base64
import json
import re
import time
import requests
import public_config

from flask import current_app, request
from apps.picture.settings import config
from apps.picture.business.picturehandlenumlocation import PictureNumLocation


class PictureNumDisBusiness(object):
    client_id = config.CLIENT_ID
    client_secret = config.CLIENT_SECRET
    token_url = config.TOKEN_URL
    headers = config.HEADERS
    
    @classmethod
    def __query_params_new(cls, dy_params={}):
        params = {x: dy_params[x] for x in dy_params.keys()}
        return params
    
    @classmethod
    def get_ai_token(cls):
        """获取百度AI识别access_token
        :return:
        """
        try:
            prefix_url = cls.__query_params_new(
                {'grant_type': 'client_credentials', 'client_id': cls.client_id,
                 'client_secret': cls.client_secret})
            base_url = requests.get(cls.token_url, prefix_url).url
            res = requests.post(base_url)
            if res.status_code == 200 and res.reason == 'OK':
                return res.json().get('access_token')
            return None
        except Exception as e:
            current_app.logger.error(str(e))
            return None
    
    @classmethod
    def handle_binary_picture(cls, picture):
        """二进制方式打开图片文件
        :param picture:
        :return:
        """
        f = open(picture, 'rb')
        img = base64.b64encode(f.read())
        return img
    
    @classmethod
    def handle_picture(cls, token):
        """通用文字识别（高精度含位置版）
        :return:
        """
        try:
            pwd = '/Users/hepengchong/Documents/test_photo/'
            photo = '6741601091743_.pic_hd.jpg'
            # photo = 'WechatIMG662.jpeg'
            url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate'
            picture = pwd + photo
            img = cls.handle_binary_picture(picture)
            prefix_url = requests.get(url, {'access_token': token}).url
            body = {
                'image': img,
                'vertexes_location': True,
                'paragraph': True,
                'probability': True
            }
            current_app.logger.info('计算开始时间:{}'.format(int(time.time())))
            res = requests.post(url=prefix_url, headers=cls.headers, data=body)
            current_app.logger.info('计算结束时间:{}'.format(int(time.time())))
            if res.status_code == 200 and res.reason == 'OK':
                result = json.loads(res.text).get('words_result')
                return result
        except Exception as e:
            current_app.logger.error(str(e))
            return None
    
    @classmethod
    def is_chinese(cls, string):
        """检查整个字符串是否包含中文
        :param string: 需要检查的字符串
        :return: 返回数字与数字对应的位置location
        """
        number = []
        for ch in string:
            num = re.findall(r'\b\d+\b', ch.get('number'))
            if len(num) == 1:
                number.append({'number': num[0], 'location': ch.get('location')})
            elif len(num) == 2:
                num = {'number': num[0] + num[1], 'location': ch.get('location')}
                number.append(num)
            elif len(num) == 0:
                continue
            else:
                number.append({'number': num, 'location': ch.get('location')})
        return number
    
    @classmethod
    def filter_num(cls, content):
        """过滤非数字
        :param content:
        :return:
        """
        int_num = [str(i) for i in range(0, 10)]
        base_content = []
        for c in content:
            for words in c.get('words'):
                if words in int_num:
                    base_content.append(c)
                    break
        words = [{'number': c.get('words'), 'location': c.get('location')} for c in base_content]
        print(words)
        base_words = cls.is_chinese(words)
        print(base_words)
        content = PictureNumLocation.diff_length_num(base_words)
        current_app.logger.info('计算后的数字有:{}'.format(content))
        # 剩余哪些数字没有识别到
        number = {c.get('number') for c in content}
        all_number = {str(i) for i in range(10)}
        surplus = list(all_number.difference(number))
        all_left = {c.get('number'): c.get('location').get('left') for c in content}
        all_top = {c.get('number'): c.get('location').get('top') for c in content}
        # 计算数字之间的间距
        location_x = ['12', '23', '45', '56', '78', '89']
        exist_num_x = [x for x in location_x if x[0] in list(number) and x[1] in list(number)]
        left_length = abs(all_left.get(exist_num_x[0][0]) - all_left.get(exist_num_x[0][1]))
        current_app.logger.info('此手机横坐标之差:{}'.format(left_length))
        # 计算纵坐标
        location_y = ['14', '25', '36', '47', '58', '69', '80']
        exist_num_y = [y for y in location_y if y[0] in list(number) and y[1] in list(number)]
        top_length = abs(all_top.get(exist_num_y[0][0]) - all_top.get(exist_num_y[0][1]))
        current_app.logger.info('此手机纵坐标之差:{}'.format(top_length))
        print(1)
        # for s in surplus:
        # 计算5的坐标
        PictureNumLocation.calculation_five_location()
        exist_ = [num for num in ['2', '4', '6', '8'] if num in number]
        if exist_[0] < '5':
            if exist_[0] == '4':
                left = all_left.get(exist_[0])
                top = all_top.get(exist_[0]) + 20
            else:
                left = all_left.get(exist_[0]) - 25
                top = all_top.get(exist_[0])
        else:
            if exist_[0] == '6':
                left = all_left.get(exist_[0])
                top = all_top.get(exist_[0]) - 20
            else:
                left = all_left.get(exist_[0]) - 25
                top = all_top.get(exist_[0])
        content.append({'number': '5', 'location': {'left': left, 'top': top}})
        print(exist_)
        #     if s in ['1', '2', '3']:
        #         # 计算横坐标
        #         exist_num = [num for num in ['1', '2', '3'] if num in list(number)]
        #         location = [c.get('location') for c in content if
        #                     c.get('number') == exist_num[0]][0] if exist_num else None
        #
        #         num_x = [num for num in ['12', '23', '45', '56', '78', '89'] if
        #                  num[0] in list(number) and num[1] in list(number)]
        #         value = num_x[0] if num_x else None
        #         content.get(value[1])
        #         print(num_x)
        # num_x = [num for num in [12, 23, 45, 56, 78, 89] ]
        
        return content
    
    @classmethod
    def diff_type_num(cls, number, location):
        """
        :param number:
        :param location:
        :return:
        """
    
    # @classmethod
    # def diff_type_num(cls, number, word):
    #     """
    #     :param number:
    #     :param word:
    #     :return:
    #     """
    #     if number == '1':
    #         if int(word) in [1, 12, 123, 14, 147]:
    #             return True
    #     if number == '2':
    #         if int(word) in [2, 23, 25, 258, 2580] or word == '2-580':
    #             return True
    #     if number == '3':
    #         if int(word) in [3, 36, 369]:
    #             return True
    #     return False
    
    # # 数字识别
    # def num():
    #     pwd = '/Users/hepengchong/Documents/test_photo/'
    #     # photo = 'WechatIMG662.jpeg'
    #     photo = 'screen.png'
    #     # photo = '6731600776807_.pic.jpg'
    #     base_photo = pwd + photo
    #     # 二进制方式打开图片文件
    #     f = open(base_photo, 'rb')
    #     img = base64.b64encode(f.read())
    #
    #     num_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/numbers?'
    #     base_url = num_url + 'access_token=' + token
    #     body_1 = {
    #         'image': img,
    #         'detect_direction': True,
    #         'recognize_granularity': 'small'
    #     }
    #     print('3', int(time.time()))
    #     res_1 = requests.post(url=base_url, headers=headers, data=body_1)
    #     print('4', int(time.time()))
    #     print()
    #     b = json.loads(res_1.text)
    #     print(b)
    #
    #
    # num()
    #
    #
    # # 文档版面分析与识别
    # def wendang():
    #     one_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/doc_analysis?'
    #     base_url = one_url + 'access_token=' + token
    #     body_2 = {
    #         'image': img,
    #         'language_type': 'CHN_ENG',
    #         'result_type': 'big',
    #         'detect_direction': False,
    #         'line_probability': True,
    #         'words_type': False,
    #         'layout_analysis': True
    #     }
    #     print('3', int(time.time()))
    #     res_2 = requests.post(url=base_url, headers=headers, data=body_2)
    #     print('4', int(time.time()))
    #     print()
    #     b = json.loads(res_2.text)
    #     print(b)
